// Created by Joe on 2017/7/14.

app.controller(
    'PeopleLivelihoodController',
    [
        'KEY', 'config', '$scope', '$location', '$timeout', '$sce', 'UserService', 'PeopleLivelihoodService',
        function (KEY, config, $scope, $location, $timeout, $sce, UserService, PeopleLivelihoodService) {
            init();

            function init() {
                // animate switch
                $.fx.off = config.forbiddenAnimate;

                // set page
                // @list: beginning position of curList in list
                // @listIndex: position of current focus
                // @listPageIndex: index of current page
                // @da: down arrow
                // @la/ra: left/right arrow <0[hidden], 1[show], 2[focus]>
                // @end: last page
                $scope.page = ['home', 'detail'];
                $scope.limit = {list: 4, listPage: 100, step: 200, height: 720 - config.borderMask};
                $scope.panel = {height: 0, top: 0, empty: false, load: false};
                $scope.control = {
                    page: 0,
                    list: 0, listIndex: 0, listPageIndex: 1,
                    la: 1, ra: 1, da: '',
                    end: false
                };

                // set selector
                $scope.selector = {
                    $news: $('.scroll'),
                    $newsContent: $('.city__pl-center .content')
                };

                // set timer
                $scope.timer = null;

                // set data
                $scope.data = {
                    list: [],
                    curList: [],
                    detail: {}
                };

                // add logic
                addLogic();

                // get info
                $scope.panel.load = true;
                PeopleLivelihoodService.getListInfo($scope.limit.listPage, $scope.control.listPageIndex)
                    .then(function (info) {
                        $scope.data.list = [];
                        info.list.forEach(function (item) {
                            $scope.data.list.push({
                                id: item['id'],
                                title: item['title'],
                                thumb: item['thumb'],
                                updateTime: item['inputtime']
                            });
                        });

                        $scope.data.curList = $scope.data.list.slice(
                            $scope.control.list, $scope.control.list + $scope.limit.list
                        );

                        if ($scope.data.list.length > $scope.limit.list)
                            $scope.control.da = 'arrow-down--blur';

                        $scope.panel.load = false;
                        $scope.panel.empty = $scope.data.list.length === 0;
                    });

                // ele action
                $scope.move = function (evt, cb) {
                    evt.preventDefault();
                    if ($scope.control.page === 1) return;
                    switch (evt.keyCode) {
                        case KEY.UP:
                            moveShim('up');
                            break;
                        case KEY.DOWN:
                            moveShim('down');
                            break;
                        case KEY.ENTER:
                            cb instanceof Function && cb();
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
                document.addEventListener('keyup', arrowAction);
            }

            function addLogic() {
                // show list
                $scope.showList = function () {
                    $scope.data.detail = {};
                    pageSwitch(0);
                };

                // show detail
                $scope.showDetail = function () {
                    // for enter check
                    $scope.control.page === 0 && pageSwitch(1);
                    arrowSwitch();
                    $timeout.cancel($scope.timer);
                    $scope.timer = $timeout(function () {
                        // method1: add data-key, method2: look for in news
                        // $('#' + document.activeElement.id).attr('data-key')
                        $scope.panel.load = true;
                        $scope.data.detail = {};
                        PeopleLivelihoodService.getDetailInfo($scope.data.curList[$scope.control.listIndex].id)
                            .then(function (info) {
                                $scope.data.detail.title = info['title'];
                                $scope.data.detail.updateTime = info['inputtime'];
                                $scope.data.detail.content = $sce.trustAsHtml(info['content']);

                                $timeout(function () {
                                    $scope.panel.height = parseInt($scope.selector.$newsContent.css('height'), 10) + 205;
                                });

                                $scope.panel.load = false;
                            });

                        $scope.panel.top = 0;
                        $scope.selector.$news.css('top', 0);
                    }, config.requestDelay);
                };

                // load next page info
                $scope.getList = function () {
                    if ($scope.data.list.length < $scope.limit.page) return;

                    $scope.panel.load = true;
                    PeopleLivelihoodService.getListInfo($scope.limit.listPage, ++$scope.control.listPageIndex)
                        .then(function (info) {
                            info.list.forEach(function (item) {
                                $scope.data.list.push({
                                    id: item['id'],
                                    title: item['title'],
                                    thumb: item['thumb'],
                                    updateTime: item['inputtime']
                                });
                            });

                            $scope.data.curList = $scope.data.list.slice(
                                ++$scope.control.list, $scope.control.list + $scope.limit.list
                            );

                            // fix lose focus bug when load last page info
                            if ($scope.data.curList.length < $scope.limit.list) {
                                $scope.data.curList = $scope.data.list.slice(
                                    --$scope.control.list, $scope.control.list + $scope.limit.list
                                );
                                $scope.control.end = true;
                            }

                            $scope.panel.load = false;
                        });
                };
            }

            function pageSwitch(page) {
                page = page || 0;
                $scope.control.page = page;
            }

            function arrowSwitch(dir, state) {
                // forbidden left arrow hidden here
                // just enable right arrow hidden
                if ($scope.control.listPageIndex === 1
                    && $scope.control.list === 0
                    && $scope.control.listIndex === 0) {
                    $scope.control.la = 0;
                } else {
                    $scope.control.la = 1;
                }

                if ($scope.control.end
                    && $scope.control.list + $scope.control.listIndex === $scope.data.list.length - 1) {
                    $scope.control.ra = 0;
                } else {
                    $scope.control.ra = 1;
                }

                if (dir === 'left') {
                    if ($scope.control.la === 0) {
                        return;
                    } else if (state === 'focus') {
                        $scope.control.la = 2;
                    } else if (state === 'show') {
                        $scope.control.la = 1;
                    }
                }

                if (dir === 'right') {
                    if ($scope.control.ra === 0) {
                        return;
                    } else if (state === 'focus') {
                        $scope.control.ra = 2;
                    } else if (state === 'show') {
                        $scope.control.ra = 1;
                    }
                }
            }

            function moveShim(dir) {
                if (dir === 'up' || dir === 'left') {
                    if ($scope.control.da && $scope.control.da !== 'arrow-down--blur') $scope.control.da = 'arrow-down--blur';
                    if ($scope.control.listIndex > 0) {
                        $scope.control.listIndex--;
                    } else {
                        if ($scope.control.list > 0) {
                            $scope.data.curList = $scope.data.list.slice(
                                --$scope.control.list, $scope.control.list + $scope.limit.list
                            );
                        }
                    }
                }

                if (dir === 'down' || dir === 'right') {
                    if ($scope.panel.load && $scope.control.listIndex === $scope.limit.list - 1) return;
                    if ($scope.control.listIndex < Math.min($scope.limit.list - 1, $scope.data.list.length - 1)) {
                        $scope.control.listIndex++;
                    } else {
                        if ($scope.control.list + $scope.limit.list < $scope.data.list.length) {
                            $scope.data.curList = $scope.data.list.slice(
                                ++$scope.control.list, $scope.control.list + $scope.limit.list
                            );
                        } else if (!$scope.control.end) {
                            $scope.getList();
                        }
                    }
                    if ($scope.control.end
                        && $scope.control.list + $scope.limit.list === $scope.data.list.length
                        && $scope.control.listIndex === $scope.limit.list - 1)
                        $scope.control.da = 'arrow-up--blur';
                }
            }

            function globalAction() {
                var up = function () {
                    if ($scope.control.page === 0) return;

                    if ($scope.panel.top < 0) {
                        $scope.panel.top += $scope.limit.step;
                        // top align
                        $scope.panel.top = $scope.panel.top < 0 ? $scope.panel.top : 0;
                        $scope.selector.$news.stop().animate({top: $scope.panel.top}, {duration: config.animateDelay});
                    }
                };
                var down = function () {
                    if ($scope.control.page === 0) return;

                    // eliminate image loading effect
                    $scope.panel.height = parseInt($scope.selector.$newsContent.css('height'), 10) + 205;
                    if ($scope.limit.height - $scope.panel.top < $scope.panel.height) {
                        $scope.panel.top -= $scope.limit.step;
                        // bottom align
                        $scope.panel.top = $scope.limit.height - $scope.panel.top < $scope.panel.height ?
                            $scope.panel.top : $scope.limit.height - $scope.panel.height;
                        $scope.selector.$news.stop().animate({top: $scope.panel.top}, {duration: config.animateDelay});
                    }
                };
                var left = function () {
                    if ($scope.control.page === 0) return;
                    moveShim('left');
                    $scope.showDetail();
                    arrowSwitch('left', 'focus');
                };
                var right = function () {
                    if ($scope.control.page === 0 || $scope.control.da === 'arrow-up--blur') return;
                    moveShim('right');
                    $scope.showDetail();
                    arrowSwitch('right', 'focus');
                };
                var back = function () {
                    if ($scope.control.page === 0) {
                        $scope.$apply(function () {
                            $location.path('/home').replace();
                        });
                    } else {
                        $scope.showList();
                        $scope.panel.load = false;
                        $scope.data.detail = {};
                    }
                };

                switch (event.keyCode) {
                    case KEY.UP:
                        up();
                        break;
                    case KEY.DOWN:
                        down();
                        break;
                    case KEY.LEFT:
                        left();
                        break;
                    case KEY.RIGHT:
                        right();
                        break;
                    case KEY.BACK:
                        back();
                        break;
                }

                $scope.$digest();
            }

            function arrowAction() {
                switch (event.keyCode) {
                    case KEY.LEFT:
                        arrowSwitch('left', 'show');
                        break;
                    case KEY.RIGHT:
                        arrowSwitch('right', 'show');
                        break;
                }

                $scope.$digest();
            }

            $scope.$on('$destroy', function () {
                $timeout.cancel($scope.timer);
                document.removeEventListener('keydown', globalAction);
                document.removeEventListener('keyup', arrowAction);
            });
        }
    ]
);



